package com.unicampmaps;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.params.HttpClientParams;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.RectF;
import android.net.Uri;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.NavUtils;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.view.MenuItem;
import com.slidingmenu.lib.SlidingMenu;
import com.slidingmenu.lib.app.SlidingFragmentActivity;

public class DetailsActivity extends SlidingFragmentActivity {
	
	public FragmentManager mFragmentManager;

	public Venue venue;
	public static long curr_venue_id;
	
	private String foursquareVenueId;
	
	private ProgressDialog mDialog;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		this.mFragmentManager = getSupportFragmentManager();

		ActionBar actionBar = this.getSupportActionBar();
        actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
        
        actionBar.setDisplayHomeAsUpEnabled(true);
        actionBar.setHomeButtonEnabled(false);
        
        actionBar.setDisplayShowTitleEnabled(true);
        actionBar.setBackgroundDrawable(getResources().getDrawable(R.drawable.actionbar_background));
        
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setHomeButtonEnabled(false);
        getSupportActionBar().setIcon(android.R.color.transparent);

        SlidingMenu slidingMenu = getSlidingMenu();
        slidingMenu.setBehindWidthRes(R.dimen.sliding_menu_width);
        slidingMenu.setBehindScrollScale(0.0f);
        slidingMenu.setTouchModeAbove(SlidingMenu.TOUCHMODE_FULLSCREEN);
        setBehindContentView(R.layout.fragment_menu);
        
        
        setContentView(R.layout.activity_details);
        getSupportFragmentManager().beginTransaction().replace(R.id.frag_menu, new MenuFragment()).commit();
        

        this.foursquareVenueId = loadVenue();
		
		setLayoutData();
        
        Button mapButton = (Button) findViewById(R.id.map_button);
		mapButton.setOnClickListener(new OnClickListener() {
	        
			@Override
			public void onClick(View arg0) {
				BasicMapViewer.emptyVenues();
				BasicMapViewer.addVenue(DetailsActivity.this.venue);
				
				Intent intent;
    			intent = new Intent(arg0.getContext(), BasicMapViewer.class);
    	        startActivity(intent);
	        }
	    });
		
		Button checkInButton = (Button) findViewById(R.id.check_in_button);
		checkInButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {

				SharedPreferences prefs = PreferenceManager
						.getDefaultSharedPreferences(arg0.getContext());
				if (prefs.getString("token", "").equals("")) {
					Intent intent = new Intent(arg0.getContext(),
							ActivityWebView.class);
					startActivity(intent);
					return;
				}

				String alert = "Não foi possível realizar o checkin";
				String s = doCheckinPost();
				try {
					alert = "Obrigado pelo checkin!";
					JSONArray notifications = (JSONArray) ((JSONObject) (new JSONObject(
							s)).get("response")).get("notifications");
					for (int i = 0; !notifications.isNull(i); i++) {
						JSONObject notification = ((JSONObject) notifications
								.get(i));
						String type = notification.getString("type");
						if (type.equals("message")) {
							alert = ((JSONObject) notification.get("item"))
									.getString("message");
						}
					}

				} catch (JSONException e) {
					e.printStackTrace();
				}
				Toast.makeText(getApplicationContext(), alert,
						Toast.LENGTH_LONG).show();

			}
		});
		
		TextView label_dicas = (TextView)findViewById(R.id.tips_label);
		label_dicas.setVisibility(View.GONE);
		TextView label_fotos = (TextView)findViewById(R.id.photos_label);
		label_fotos.setVisibility(View.GONE);
		LinearLayout list = (LinearLayout)findViewById(R.id.tips_view);
		list.setVisibility(View.GONE);
		
		//Chama o update via internet
		FoursquareVenueFetcher fetcher = new FoursquareVenueFetcher(this.foursquareVenueId,this,getCacheDir().getAbsolutePath());
		fetcher.execute(fetcher.getTips(), fetcher.getPhotos());
		
		mDialog = new ProgressDialog(this);
        mDialog.setMessage("Loading...");
        mDialog.setCancelable(true);
        mDialog.show();
	}
	
	private String loadVenue() {
		String[] projection = { 
			    VenueData.C_ID,
			    VenueData.C_FOURSQUARE_VENUE_ID,
			    VenueData.C_TYPE,
			    VenueData.C_NAME,
			    VenueData.C_ABBR,
			    VenueData.C_ADDRESS,
			    VenueData.C_LATITUDE, 
			    VenueData.C_LONGITUDE,
			    VenueData.C_PHONE_NUMBER, 
			    VenueData.C_SITE,
			    VenueData.C_IMAGE};
		
		//Busca pelo id de ponto de interesse
		Uri uri = Uri.parse(VenueProvider.CONTENT_URI + "/" + VenueData.C_ID + "/" + DetailsActivity.curr_venue_id);
		Cursor cursor = getContentResolver().query(uri, projection, null, null, null);
		String foursquare_venue_id="";
		if (cursor != null) {
			cursor.moveToFirst();
			
			for (int i = 0; i < cursor.getCount(); i++) {
				int id = cursor.getInt(cursor.getColumnIndexOrThrow(VenueData.C_ID));
				foursquare_venue_id = cursor.getString(cursor.getColumnIndexOrThrow(VenueData.C_FOURSQUARE_VENUE_ID));
				int type = cursor.getInt(cursor.getColumnIndexOrThrow(VenueData.C_TYPE));
				String name = cursor.getString(cursor.getColumnIndexOrThrow(VenueData.C_NAME));
				String abbr = cursor.getString(cursor.getColumnIndexOrThrow(VenueData.C_ABBR));
				String address = cursor.getString(cursor.getColumnIndexOrThrow(VenueData.C_ADDRESS));
				float latitude = cursor.getFloat(cursor.getColumnIndexOrThrow(VenueData.C_LATITUDE));
				float longitude = cursor.getFloat(cursor.getColumnIndexOrThrow(VenueData.C_LONGITUDE));
				String phone_number = cursor.getString(cursor.getColumnIndexOrThrow(VenueData.C_PHONE_NUMBER));
				String site = cursor.getString(cursor.getColumnIndexOrThrow(VenueData.C_SITE));
				String image = cursor.getString(cursor.getColumnIndexOrThrow(VenueData.C_IMAGE));
		        
				System.out.println("name loaded: " + name);
				
				this.venue = new Venue(id, foursquare_venue_id, type, name, abbr, address, latitude, longitude, phone_number, site, image);
		        
		        cursor.moveToNext();
			}
			cursor.close();
		}
		return foursquare_venue_id;
	}
	
	private void setLayoutData() {
		View tempView = findViewById(R.id.details_view);
		
		TextView subtitle = (TextView) tempView.findViewById(R.id.subtitle);
		
		TextView site = (TextView) tempView.findViewById(R.id.site);
		
		getSupportActionBar().setTitle(this.venue.getName());
		
		if (this.venue.getAbbr().trim().equals("")) {
			subtitle.setVisibility(View.GONE);
		} else {
			subtitle.setText(this.venue.getAbbr());
			subtitle.setVisibility(View.VISIBLE);
		}
		

		if (this.venue.getSite().trim().equals("")) {
			site.setVisibility(View.GONE);
		} else {
			site.setText(this.venue.getSite());
			site.setVisibility(View.VISIBLE);
			
			site.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View arg0) {
					Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(DetailsActivity.this.venue.getSite()));
					startActivity(browserIntent);
				}
			});
		}
	}
	
	public void fillData(FoursquareVenueData foursquareVenueData){
		TextView label_dicas = (TextView)findViewById(R.id.tips_label);
		TextView label_fotos = (TextView)findViewById(R.id.photos_label);
		LinearLayout list = (LinearLayout)findViewById(R.id.tips_view);
		
		ExpandableHeightGridView grid = (ExpandableHeightGridView)findViewById(R.id.photos_view);
		grid.setExpanded(true);
		grid.setOnItemClickListener(new OnItemClickListener() {
	        @Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int position, long id) {
	        	ImageAdapter adapter = (ImageAdapter)arg0.getAdapter();
	        	if (adapter.bitmapList != null &&
        			adapter.bitmapList.size() > position) {
	        		Bitmap bitmap = adapter.bitmapList.get(position);
	        		Intent i = new Intent(arg0.getContext(), ImageViewer.class);
		    		ImageViewer.image = bitmap;
		    		arg0.getContext().startActivity(i);
	        	}
	        }
		});
		
		if (foursquareVenueData.tips.size() > 0) {
			
			for (String tip : foursquareVenueData.tips) {
			    LayoutInflater inflater = LayoutInflater.from(this);
				View tempView = inflater.inflate(R.layout.tip_item, null);
				TextView tipView = (TextView) tempView.findViewById(R.id.tip);
				tipView.setText(tip);
				tipView.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT));
				
				list.addView(tempView);
			}
		} else {
			LayoutInflater inflater = LayoutInflater.from(this);
			View tempView = inflater.inflate(R.layout.tip_item, null);
			TextView tipView = (TextView) tempView.findViewById(R.id.tip);
			tipView.setText("Não há dicas por aqui!");
			tipView.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT));
			
			list.addView(tempView);
		}
		
		grid.setAdapter(new ImageAdapter(this, foursquareVenueData.photos));
		
		if (foursquareVenueData.photos.size() == 0) {
			label_fotos.setVisibility(View.GONE);
		} else {
			label_fotos.setVisibility(View.VISIBLE);
		}
		
		label_dicas.setVisibility(View.VISIBLE);
		list.setVisibility(View.VISIBLE);
		
		mDialog.dismiss();
	}
	
	private class ImageAdapter extends BaseAdapter {
		private Context mContext;
		private List<Bitmap> bitmapList;
		
		public ImageAdapter(Context mContext, List<Bitmap> bitmapList) {
			super();
			this.mContext = mContext;
			this.bitmapList = bitmapList;
		}

		@Override
        public View getView(int position, View convertView, ViewGroup container) {
			ImageView imageView = new ImageView(this.mContext);
			
			DisplayMetrics metrics = this.mContext.getResources().getDisplayMetrics();
			int mOutputX = (metrics.widthPixels/3) - 20;//Menos o espaçamento entre os itens
			int mOutputY = mOutputX;
			
			Bitmap mBitmap = this.scaleCenterCrop(this.bitmapList.get(position), mOutputX, mOutputY);			
			imageView.setImageBitmap(mBitmap);
            return imageView;
        }

		@Override
		public int getCount() {
			return this.bitmapList.size();
		}

		@Override
		public Object getItem(int arg0) {
			// TODO Auto-generated method stub
			return null;
		}

		@Override
		public long getItemId(int arg0) {
			// TODO Auto-generated method stub
			return 0;
		}
		
		public Bitmap scaleCenterCrop(Bitmap source, int newHeight, int newWidth) {
		    int sourceWidth = source.getWidth();
		    int sourceHeight = source.getHeight();

		    // Compute the scaling factors to fit the new height and width, respectively.
		    // To cover the final image, the final scaling will be the bigger 
		    // of these two.
		    float xScale = (float) newWidth / sourceWidth;
		    float yScale = (float) newHeight / sourceHeight;
		    float scale = Math.max(xScale, yScale);

		    // Now get the size of the source bitmap when scaled
		    float scaledWidth = scale * sourceWidth;
		    float scaledHeight = scale * sourceHeight;

		    // Let's find out the upper left coordinates if the scaled bitmap
		    // should be centered in the new size give by the parameters
		    float left = (newWidth - scaledWidth) / 2;
		    float top = (newHeight - scaledHeight) / 2;

		    // The target rectangle for the new, scaled version of the source bitmap will now
		    // be
		    RectF targetRect = new RectF(left, top, left + scaledWidth, top + scaledHeight);

		    // Finally, we create a new bitmap of the specified size and draw our new,
		    // scaled bitmap onto it.
		    Bitmap dest = Bitmap.createBitmap(newWidth, newHeight, source.getConfig());
		    Canvas canvas = new Canvas(dest);
		    canvas.drawBitmap(source, null, targetRect, null);

		    return dest;
		}
    }

	
	private DefaultHttpClient createHttpClient() {
		final SchemeRegistry supportedSchemes = new SchemeRegistry();

		supportedSchemes.register(new Scheme("http", PlainSocketFactory
				.getSocketFactory(), 80));
		supportedSchemes.register(new Scheme("https", SSLSocketFactory
				.getSocketFactory(), 443));

		final HttpParams params = new BasicHttpParams();

		HttpConnectionParams.setConnectionTimeout(params,
				FoursquareVenueFetcher.TIMEOUT * 1000);
		HttpConnectionParams.setSoTimeout(params,
				FoursquareVenueFetcher.TIMEOUT * 1000);
		HttpConnectionParams.setSocketBufferSize(params, 8192);

		HttpClientParams.setRedirecting(params, false);

		final ClientConnectionManager com = new ThreadSafeClientConnManager(
				params, supportedSchemes);

		return new DefaultHttpClient(com, params);
	}

	private String doCheckinPost() {
		try {
			HttpPost httpPost = new HttpPost(
					"https://api.foursquare.com/v2/checkins/add");

			DefaultHttpClient httpClient = createHttpClient();

			SharedPreferences prefs = PreferenceManager
					.getDefaultSharedPreferences(getApplicationContext());

			List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
			nameValuePairs.add(new BasicNameValuePair("venueId",
					this.foursquareVenueId));
			nameValuePairs.add(new BasicNameValuePair("oauth_token", prefs
					.getString("token", "")));
			nameValuePairs.add(new BasicNameValuePair("v", "20130621"));
			httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

			HttpResponse httpResponse;

			httpResponse = httpClient.execute(httpPost);
			String response = EntityUtils.toString(httpResponse.getEntity());

			return response;
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return "";
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		System.out.println("CLICOU");
		System.out.println(item.getItemId());
		System.out.println(android.R.id.home);
		switch (item.getItemId()) {
	      case android.R.id.home:
	         // This ID represents the Home or Up button. In the case of this
	         // activity, the Up button is shown. Use NavUtils to allow users
	         // to navigate up one level in the application structure. For
	         // more details, see the Navigation pattern on Android Design:
	         //
	         // http://developer.android.com/design/patterns/navigation.html#up-vs-back
	         //
	         NavUtils.navigateUpTo(this,
	               new Intent(this, DetailsActivity.class));
	         return true;
	   }
	   return super.onOptionsItemSelected(item);
	}

}
